<template>
  <a-modal v-model:visible="visible" title="选择对应流程">
    <a-table :row-selection="rowSelection" :columns="columns" :data-source="data" :pagination="false" :scroll="{ y: '50vh' }" rowKey="id" size="small"> </a-table>
    <template #footer>
      <a-space>
        选择了：{{ chosProcess.name }}
        <a-button key="cancel" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" :disabled="chosProcess.name ? false : true" @click="handleOk">确定</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script lang="ts">
import { message } from 'ant-design-vue'
import { defineComponent, onUpdated, ref, Ref, toRaw } from 'vue'
import { get } from '../../utils/request/request'

const columns = [
  {
    title: '流程名称',
    dataIndex: 'name',
    align: 'center',
    ellipsis: true
  }
]

interface DataItem {
  id: number | undefined
  name: string
}

const data: Ref<DataItem[]> = ref([])

//表格数据
const useTabelEffect = () => {
  const chosProcess = ref<DataItem>({
    id: undefined,
    name: ''
  })
  const rowSelection = {
    type: 'radio',
    onSelect: (record: DataItem) => {
      chosProcess.value = record
      // console.log(record.name,record.id,record.app_id)
    }
  }
  return {
    chosProcess,
    columns,
    rowSelection
  }
}

// 网络请求
const useHttpEffect = (token: string) => {
  const getData = async () => {
    const res: any = await get(`/admin/api/v1/recruitment/process/list?page=1&limit=100`, token)
    console.log(res)
    if (res.status_code === 0) {
      if (res.data == null) {
        message.info('没有数据')
      } else {
        data.value = res.data
      }
    }
  }
  return { getData }
}

// modal相关
const useModalEffect = (chosProcess: Ref<DataItem>, emit: any) => {
  const visible = ref<boolean>(false)
  const showModal = () => {
    visible.value = true
  }
  const handleOk = () => {
    if (chosProcess.value.name) {
      visible.value = false
      emit('chosItem', toRaw(chosProcess.value))
    } else {
      message.warn('您没有选择流程')
    }
  }
  const handleCancel = () => {
    visible.value = false
  }
  return {
    visible,
    showModal,
    handleOk,
    handleCancel
  }
}

export default defineComponent({
  emits: ['chosItem'],
  props: ['chosTitle'],
  setup(props, { emit }) {
    const token: string = localStorage.getItem('token') as string
    const { chosProcess, columns, rowSelection } = useTabelEffect()
    const { visible, showModal, handleOk, handleCancel } = useModalEffect(chosProcess, emit)
    const { getData } = useHttpEffect(token)

    onUpdated(() => {
      if (visible.value) {
        getData()
      }
    })
    return {
      visible,
      showModal,
      handleOk,
      handleCancel,
      chosProcess,
      data,
      columns,
      rowSelection
    }
  }
})
</script>
